import React, { Component } from 'react';
import { withRouter, Link } from 'react-router-dom';
import { Layout, Menu, Icon } from 'antd';
import routes from '@/routes/config';

class SiderCustom extends Component {

  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      firstHide: false, // 点击收缩菜单，第一次隐藏展开子菜单，openMenu时恢复
      openKey: '',
      selectedKey: ''
    };
  }

  static getDerivedStateFromProps(props, state) {
    const { collapsed, selectedKey } = state;
    if (props.collapsed !== collapsed) {
      return {
        collapsed: props.collapsed,
        firstHide: props.collapsed, // 两个不等时赋值props属性值否则为false
        openKey: selectedKey.substr(0, selectedKey.lastIndexOf('/'))
      }
    }
    return false;
  }

  componentDidMount() {
    const { pathname } = this.props.location;
    this.setState({
      openKey: pathname.substr(0, pathname.lastIndexOf('/')),
      selectedKey: pathname
    });
  }

  handleClickMenu({key}) {
    this.setState({
      selectedKey: key
    });
    // 响应式布局控制小屏幕点击菜单时隐藏菜单操作
    // eslint-disable-next-line
    this.props.fnPopoverHide?.();
  };

  renderMenuItem(item) {
      return (
        <Menu.Item key={item.key}>
          <Link to={item.key + (item.query || '')}> 
            {item.icon && <Icon type={item.icon} />}
            <span>{item.title}</span>
          </Link>
      </Menu.Item>
      );
  }

  renderSubMenu(item) {
      return (
        <Menu.SubMenu key={item.key} title={<span>{item.icon && <Icon type={item.icon} />}<span>{item.title}</span></span>}>
          {item.subs.map(item => this.renderMenuItem(item))}
        </Menu.SubMenu>
      );
  }
  dynamicLoadingChannel(item){
      return item;
  }

  render() {
    const { collapsed } = this.props;
    const { selectedKey, openKey, firstHide } = this.state;
    return (
      <Layout.Sider className="rs-sider" trigger={null} breakpoint="lg" collapsed={collapsed} theme="light">
        <Menu mode="inline" 
          selectedKeys={[selectedKey]} 
          openKeys={firstHide ? null : [openKey]} 
          onClick={this.handleClickMenu.bind(this)}
          onOpenChange={(keys) => this.setState({ openKey: keys[keys.length - 1], firstHide: false })}
        >
          {routes.menus?.map(item => item.subs ? this.renderSubMenu(this.dynamicLoadingChannel(item)) : this.renderMenuItem(item))}
        </Menu>
      </Layout.Sider>
    )
  }
}

export default withRouter(SiderCustom);
